package edu.ads.bookloan

import edu.ads.bookloan.LatestAvailableBookSingleton

import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
import org.springframework.dao.DataIntegrityViolationException


class LoanHistoryController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	def springSecurityService
	static navigation = [
		[group:'tabs', action:'list',title:'Loan History', order: 0, isVisible: { SpringSecurityUtils.ifAnyGranted("ROLE_ADMIN,ROLE_EMPLOYEE,ROLE_STUDENT") }]
	]

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
		def currentUser = springSecurityService.principal
		def loanHistoryList
		params.max = Math.min(max ?: 10, 100)
		ResultStrategy resultStrategy = ResultStrategyFactory.createStrategy(currentUser)
		loanHistoryList = resultStrategy.getResult(params)
        [loanHistoryInstanceList: loanHistoryList, loanHistoryInstanceTotal: LoanHistory.count()]
    }

	def returnBookLoan()
	{
		LoanHistory loanHistory = LoanHistory.get(params?.id)
		loanHistory.dateReturned = new Date()
		loanHistory.inventoryItem.inventoryItemStatus = InventoryItemStatus.findByStatus('Available')
		loanHistory.save(flush: true,failOnError: true)
		loanHistory.inventoryItem.save(flush: true,failOnError: true)
		flash.message = "The Book ${loanHistory.inventoryItem} has been returned successfully"	
		
		LatestAvailableBookSingleton instance = LatestAvailableBookSingleton.getInstance()
		instance.setLatestAvailableBook(loanHistory.inventoryItem.book)
		render(view: "show", model: [loanHistoryInstance: loanHistory])
	}

	
    def create() {
        [loanHistoryInstance: new LoanHistory(params)]
    }

    def save() {
        def loanHistoryInstance = new LoanHistory(params)
        if (!loanHistoryInstance.save(flush: true)) {
            render(view: "create", model: [loanHistoryInstance: loanHistoryInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'loanHistory.label', default: 'LoanHistory'), loanHistoryInstance.id])
        redirect(action: "show", id: loanHistoryInstance.id)
    }

    def show(Long id) {
        def loanHistoryInstance = LoanHistory.get(id)
        if (!loanHistoryInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'loanHistory.label', default: 'LoanHistory'), id])
            redirect(action: "list")
            return
        }

        [loanHistoryInstance: loanHistoryInstance]
    }

    def edit(Long id) {
        def loanHistoryInstance = LoanHistory.get(id)
        if (!loanHistoryInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'loanHistory.label', default: 'LoanHistory'), id])
            redirect(action: "list")
            return
        }

        [loanHistoryInstance: loanHistoryInstance]
    }

    def update(Long id, Long version) {
        def loanHistoryInstance = LoanHistory.get(id)
        if (!loanHistoryInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'loanHistory.label', default: 'LoanHistory'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (loanHistoryInstance.version > version) {
                loanHistoryInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'loanHistory.label', default: 'LoanHistory')] as Object[],
                          "Another user has updated this LoanHistory while you were editing")
                render(view: "edit", model: [loanHistoryInstance: loanHistoryInstance])
                return
            }
        }

        loanHistoryInstance.properties = params

        if (!loanHistoryInstance.save(flush: true)) {
            render(view: "edit", model: [loanHistoryInstance: loanHistoryInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'loanHistory.label', default: 'LoanHistory'), loanHistoryInstance.id])
        redirect(action: "show", id: loanHistoryInstance.id)
    }

    def delete(Long id) {
        def loanHistoryInstance = LoanHistory.get(id)
        if (!loanHistoryInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'loanHistory.label', default: 'LoanHistory'), id])
            redirect(action: "list")
            return
        }

        try {
            loanHistoryInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'loanHistory.label', default: 'LoanHistory'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'loanHistory.label', default: 'LoanHistory'), id])
            redirect(action: "show", id: id)
        }
    }
	
	
	def availableBook(){
		LatestAvailableBookSingleton instance = LatestAvailableBookSingleton.getInstance()
		Book book = instance.latestAvailableBook
		Date addDate = instance.addDate
		def responseMsg = ""
		if(book){
			responseMsg = "The book $book is available since $addDate"
		}
		render responseMsg
	}
}
